/** Simple RMI client program:

   RMI client in a two-way communication. The client like server is a RMI server.
It registers its remote object with server so that the server can call the client
object's method to put the data in its text area.

*/
import java.rmi.*;
import java.rmi.server.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleClient2 extends JFrame implements MessageReceiver, ActionListener {
   static JTextArea		ta = new JTextArea();
   static JTextField		tf = new JTextField();
   static MessageReceiver	rmiServerObj = null;
   static private String	myName = null;
   transient String		tmpStr;

   public SimpleClient2 (String title) throws RemoteException {
	super(title);
	Container c = getContentPane();
	c.add(ta, BorderLayout.CENTER);
	c.add(tf, BorderLayout.SOUTH);
	tf.addActionListener(this);
	setSize(400, 300);
	setVisible(true);

	UnicastRemoteObject.exportObject( this );
   }

   public void actionPerformed(ActionEvent e) {
	if ( e.getSource() == tf ) {
		try {
			tmpStr = tf.getText().trim();
			if ( tmpStr.length() > 0 ) rmiServerObj.write(myName, tmpStr);
		} catch ( RemoteException re ) { re.printStackTrace() ; }
		tf.setText("");
	}
   }

   public void showMessage(String msg) throws RemoteException {
	ta.append(msg + '\n');
	ta.setCaretPosition(ta.getText().length() -1 );
   }

   public void write(String name, String msg) throws RemoteException {}
   public int register(String name, MessageReceiver m) { return 0; }

   public static void main( String arg[] ) {

	if ( arg.length < 2 ) {
		System.out.println("Usage: java SimpleClient2 hostName clientName");
		System.exit(-1);
	}

	try {
		myName = arg[1];

		// The remote object on client side has the name registered in server
		// rmiregistry. Not the class name used in implementation of server code while
		// The registered remote object's name could be the same of server class name.
		
		rmiServerObj = (MessageReceiver) Naming.lookup("//" + arg[0] + "/" + MessageReceiver.serverName);

		SimpleClient2 rmiClientObj = new SimpleClient2("Client name: " + myName +
				", Server: " + arg[0]);

		rmiClientObj.setSize(400, 300);
		rmiClientObj.setVisible(true);

		try {
			int i = rmiServerObj.register(arg[1], rmiClientObj);
			if ( i == MessageReceiver.REGISTRY_SUCCEED )
				System.out.println("Client object is registered with server.");
			else
				System.out.println("Client object cannot be registered with server.");


		} catch (RemoteException e) { e.printStackTrace() ; }

	} catch (Exception e) { e.printStackTrace(); }

   }
}
